<template>
  <div class="app-container">
    <!-- 左侧导航栏（Element Plus风格） -->
    <div class="sidebar">
      <div class="logo-area">
        <div class="logo">
          <el-icon class="el-icon-fish"><i class="el-icon-fish"></i></el-icon>
          <span>别看了空军佬，这里没鱼</span>
        </div>
      </div>

      <el-menu active-text-color="#ffd04b" background-color="#304156" text-color="#fff" class="el-menu-vertical-demo"
        :default-active="currentRouteName" unique-opened router>
        <!-- 其他导航项 -->
        <el-menu-item index="/main" :class="[{ 'main-active': currentRouteName === 'Main' }]">
          <el-icon>
            <component :is="'ElIconMapLocation'" />
          </el-icon>
          <span>钓鱼助手首页</span>
        </el-menu-item>
        <el-menu-item index="/map" :class="[{ 'main-active': currentRouteName === 'Map' }]">
          <el-icon>
            <component :is="'ElIconMapLocation'" />
          </el-icon>
          <span>此地有鱼地图</span>
        </el-menu-item>

        <!-- <el-menu-item index="/fish" :class="[{ 'main-active': currentRouteName === 'Fish' }]">
          <el-icon>
            <component :is="'ElIconFish'" />
          </el-icon>
          <span>全国鱼类大全</span>
        </el-menu-item> -->

        <!-- 二手渔具基地模块 -->
        <el-sub-menu index="/gear" :class="[{ 'main-active': isGearModuleActive }]">
          <template #title>
            <el-icon>
              <component :is="'ElIconShoppingCart'" />
            </el-icon>
            <span>二手渔具基地</span>
          </template>

          <!-- 子菜单项 -->
          <el-menu-item index="/gear/market" :class="[{ 'sub-active': currentRouteName === 'GearMarket' }]">
            <span>基地首页</span>
          </el-menu-item>

          <el-menu-item index="/gear/selling" :class="[{ 'sub-active': currentRouteName === 'MySelling' }]">
            <span>我的出售</span>
          </el-menu-item>

          <el-menu-item index="/gear/sales" :class="[{ 'sub-active': currentRouteName === 'MySales' }]">
            <span>销售订单</span>
          </el-menu-item>

          <el-menu-item index="/gear/buying" :class="[{ 'sub-active': currentRouteName === 'MyBuying' }]">
            <span>我的购买</span>
          </el-menu-item>

          <el-menu-item index="/gear/cart" :class="[{ 'sub-active': currentRouteName === 'Cart' }]">
            <span>购物车</span>
          </el-menu-item>

          <el-menu-item index="/gear/favorites" :class="[{ 'sub-active': currentRouteName === 'FavoriteList' }]">
            <span>我的收藏</span>
          </el-menu-item>
        </el-sub-menu>
        <!-- 空军佬的社区模块 -->
        <el-sub-menu index="/community" :class="[{ 'main-active': isCommunityModuleActive }]">
          <template #title>
            <el-icon>
              <component :is="'ElIconChatDotRound'" />
            </el-icon>
            <span>空军佬的社区</span>
          </template>

          <!-- 子菜单项 -->
          <el-menu-item index="/community/CommunityHome"
            :class="[{ 'sub-active': currentRouteName === 'communityHome' }]">
            <span>社区首页</span>
          </el-menu-item>

          <el-menu-item index="/community/myPresentation"
            :class="[{ 'sub-active': currentRouteName === 'MyPresentation' }]">
            <span>我的发表</span>
          </el-menu-item>
        </el-sub-menu>

        <!-- 个人中心 -->
        <el-menu-item index="/user-center" :class="[{ 'main-active': currentRouteName === 'UserCenter' }]">
          <el-icon>
            <component :is="'ElIconUser'" />
          </el-icon>
          <span>个人中心</span>
        </el-menu-item>
      </el-menu>
    </div>

    <!-- 右侧内容区 -->
    <div class="main-container">
      <div class="header">
        <h2>{{ currentNavName }}</h2>
        <div class="user-info">
          <div class="user-avatar" @click="router.push('/user-center')">{{ userInfo.avatar }}</div>
          <span @click="router.push('/user-center')" style="cursor: pointer;">{{ userInfo.name }}</span>
          <el-button style="margin-left: 10px;" size="default" class="logout-btn" @click="handleLogout">退出</el-button>
        </div>
      </div>
      <div class="content">
        <router-view></router-view>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { userAPI } from '@/api'

export default {
  name: 'MainLayout',
  setup() {
    const router = useRouter()
    const route = useRoute()

    // 用户信息
    const userInfo = ref({
      name: '你个空军佬还不登录',
      avatar: '钓'
    })

    // 验证token是否有效
    const isValidToken = (token) => {
      if (!token || token.trim() === '') {
        return false
      }
      
      // 简单的token格式验证（可以根据实际token格式调整）
      try {
        // 如果是JWT token，检查格式
        if (token.includes('.')) {
          const parts = token.split('.')
          if (parts.length !== 3) {
            return false
          }
          
          // 检查token是否过期（简单检查）
          try {
            const payload = JSON.parse(atob(parts[1]))
            if (payload.exp && payload.exp < Date.now() / 1000) {
              return false
            }
          } catch (e) {
            // 如果解析失败，可能是无效token
            return false
          }
        }
        
        return true
      } catch (error) {
        return false
      }
    }

    // 获取用户信息
    const fetchUserInfo = async () => {
      const token = localStorage.getItem('token')
      
      // 如果没有token或token无效，直接设置为未登录状态
      if (!isValidToken(token)) {
        userInfo.value = {
          name: '未登录',
          avatar: '未'
        }
        return
      }
      
      try {
        console.log('MainLayout: 获取用户信息')
        const response = await userAPI.getUserInfo()
        if (response.code === 0 && response.data) {
          console.log('MainLayout: 用户信息响应:', response.data)
          userInfo.value = {
            name: response.data.nickName || response.data.username || '钓鱼爱好者',
            avatar: (response.data.nickName || response.data.username || '钓').charAt(0)
          }
          console.log('MainLayout: 更新后的用户信息:', userInfo.value)
          // 同步保存到本地，供其他页面（如我的发表）使用
          try {
            localStorage.setItem('userInfo', JSON.stringify(response.data))
          } catch {}
        } else {
          // 响应失败，清除token并重置用户状态
          localStorage.removeItem('token')
          localStorage.removeItem('authToken')
          localStorage.removeItem('userInfo')
          userInfo.value = {
            name: '未登录',
            avatar: '未'
          }
        }
      } catch (error) {
        // 静默处理所有错误，避免在控制台显示错误信息
        console.log('MainLayout: 获取用户信息失败，设置为未登录状态')
        
        // 清除可能无效的token
        localStorage.removeItem('token')
        localStorage.removeItem('authToken')
        localStorage.removeItem('userInfo')
        
        // 重置用户状态
        userInfo.value = {
          name: '未登录',
          avatar: '未'
        }
      }
    }

    // 路由相关计算属性
    const currentRouteName = computed(() => route.name)
    const currentNavName = computed(() => {
      return '一站式钓鱼助手'
    })

    // 二手渔具模块激活状态判断
    const isGearModuleActive = computed(() => {
      return ['GearMarket', 'MySelling', 'MyBuying', 'Cart', 'ProductDetail', 'FavoriteList', 'OrderDetail'].includes(currentRouteName.value)
    })
    const isCommunityModuleActive = computed(() => {
      return ['CommunityHome', 'MyPresentation'].includes(currentRouteName.value)
    })

    // 退出登录
    const handleLogout = () => {
      ElMessageBox.confirm('确定要退出登录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 清除所有登录相关的本地存储
        localStorage.removeItem('token')
        localStorage.removeItem('authToken')
        localStorage.removeItem('userInfo')
        ElMessage.success('退出成功')
        // 延迟跳转，让用户看到提示消息
        setTimeout(() => {
          router.push('/userLogin')
        }, 500)
      }).catch(() => { })
    }

    return {
      userInfo,
      currentRouteName,
      currentNavName,
      isGearModuleActive,
      isCommunityModuleActive,
      handleLogout,
      fetchUserInfo
    }
  },
  mounted() {
    // 组件挂载后获取用户信息
    this.fetchUserInfo()
    
    // 监听用户信息更新事件
    window.addEventListener('userInfoUpdated', this.fetchUserInfo)
  },
  beforeUnmount() {
    // 组件卸载前移除事件监听器
    window.removeEventListener('userInfoUpdated', this.fetchUserInfo)
  }
}
</script>
<style scoped>
.app-container {
  display: flex;
  width: 100%;
  min-height: 100vh;
  font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", Arial, sans-serif;
}

.sidebar {
  position: fixed;
  width: 220px;
  background: linear-gradient(180deg, #304156 0%, #1f2d3d 100%);
  color: #fff;
  box-shadow: 2px 0 6px rgba(0, 21, 41, 0.35);
  z-index: 100;
  overflow-y: auto;
  height: 100vh;
}

.logo-area {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.logo {
  font-size: 15px;
  font-weight: bold;
  color: #409EFF;
  display: flex;
  align-items: center;
}

.logo .el-icon-fish {
  margin-right: 8px;
  font-size: 24px;
}

/* 导航菜单样式 */
:deep(.el-menu) {
  border-right: none;
}

:deep(.el-menu-item),
:deep(.el-sub-menu__title) {
  transition: all 0.3s;
}

:deep(.el-menu-item:hover),
:deep(.el-sub-menu__title:hover) {
  background-color: rgba(255, 255, 255, 0.1) !important;
}

:deep(.el-menu-item.is-active) {
  color: #ffd04b !important;
}

/* 主导航激活状态 */
:deep(.el-menu-item.main-active),
:deep(.el-sub-menu.is-active .el-sub-menu__title) {
  background-color: rgba(64, 158, 255, 0.2) !important;
}

/* 子导航激活状态 */
:deep(.el-menu-item.sub-active) {
  background-color: rgba(0, 0, 0, 0.2) !important;
}

.main-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  margin-left: 220px;
  overflow: hidden;
  /* 防止内容溢出 */
}


.header {
  position: fixed;
  top: 0;
  right: 0;
  left: 220px;
  /* 与左侧导航宽度一致 */
  height: 60px;
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  padding: 0 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  z-index: 99;
  /* 确保在内容区上方 */
}
.user-info {
  display: flex;
  align-items: center;
  margin-right: 30px; /* 调整距离右侧的距离 */
}
.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #409EFF;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10px;
  font-weight: bold;
}

.content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background-color: #f5f7fa;
  margin-top: 60px;
  /* 为固定头部腾出空间 */
}

.logout-btn {
  padding: 8px 16px; /* 增大按钮内边距 */
  font-size: 14px;   /* 增大字体 */
}

@media (max-width: 768px) {
  .sidebar {
    width: 64px;
  }

  .logo span,
  .el-menu :deep(.el-sub-menu__title span),
  .el-menu :deep(.el-menu-item span) {
    display: none;
  }

  .el-menu :deep(.el-sub-menu__icon-arrow),
  .nav-arrow {
    display: none;
  }

  .el-menu :deep(.el-menu-item),
  .el-menu :deep(.el-sub-menu__title) {
    justify-content: center;
  }

  .el-menu :deep(.el-menu-item i),
  .el-menu :deep(.el-sub-menu__title i) {
    margin-right: 0;
    font-size: 20px;
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .header {
    left: 64px;
    /* 移动端时左侧导航宽度变为64px */
  }

  .main-container {
    margin-left: 64px;
  }
}
</style>